package com.eportal.service.impl;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eportal.action.background.pojo.Page;
import com.eportal.aop.LogAnnotation;
import com.eportal.api.MdOpenAddTShelvesJson;
import com.eportal.api.MdOpenApi;
import com.eportal.api.MdOpenBaseJson;
import com.eportal.base.BaseDAO;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TCommunity;
import com.eportal.domain.TShelves;
import com.eportal.domain.TStrategy;
import com.eportal.exception.JdbcException;
import com.eportal.exception.MdKnownRunTimeException;
import com.eportal.service.TAgentService;
import com.eportal.service.TCommunityService;
import com.eportal.service.TShelvesService;
import com.eportal.util.Config;
import com.eportal.util.UploadUtil;
import com.eportal.util.ValidateUtil;


@Service("tShelvesService")
public class TShelvesServiceImpl  implements TShelvesService {
	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(TShelvesServiceImpl.class.getName());
	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }
	@Resource(name="dao")
	private BaseDAO dao;
	@Autowired
    private TCommunityService tCommunityService;
	@Autowired
	private TAgentService tAgentService;
    @Override
    public TShelves add(TShelves tShelves) throws Exception {
    	dao.save(tShelves);
        return tShelves;
    }

    @Override
    public void update(TShelves tshelves) throws JdbcException {
    	 dao.update(tshelves);
    }

    @Override
    public void delete(long id) {
            TShelves tshelves = (TShelves) dao.getById(TShelves.class, id);
           dao.delete(tshelves);
    }


    @Override
    public Page find(String where, Page page) {
        StringBuffer countsql = new StringBuffer("select count(t.sid) from tshelves t left join  t02_agtent a on t.agtcode=a.agtcode ");
        countsql.append(where);
        int count = dao.count(countsql.toString());
        StringBuffer listSql = new StringBuffer(""
        		+ "select * from "
        		+ "(select bb.*,rownum rownum_bb from "
        		+ "(select t.*,to_char(s.timefrom,'yyyy-MM-dd')as timefrom ,to_char(s.timeto,'yyyy-MM-dd')as timeto,s.expiredtime,s.showtime,a.agtName "
        		+ "from tshelves t "
        		+ "left join tstrategy s on t.sid=s.shid "
        		+ "left join  t02_agtent a on t.agtcode=a.agtcode ");
        listSql.append(where);
        listSql.append(" order by t.sid DESC ) bb where rownum<=");
        listSql.append((page.getCurrentPage() * page.getPageSize()));
        listSql.append(")  where rownum_bb>");
        listSql.append((page.getCurrentPage() - 1) * page.getPageSize());
        List<Map<String, Object>> list = dao.queryBySql(listSql.toString());
        return new Page(page.getCurrentPage(), page.getPageSize(), count, list);
    }

    @Override
    public TShelves get(long id) {
        return (TShelves) dao.getById(TShelves.class, id);
    }

    final static String TSHELVESPATH="/upload/tshelves/";
	@Override
	@LogAnnotation(operateDescribe="开门惊喜资源上架")  
	public Map<String, Object> addMethod(TShelves tShelves, File file, String fileName) throws Exception{
		if (file != null) {
			if ("I".equals(tShelves.getType())) {
				boolean isImage = ValidateUtil.isImage(file);
				if (!isImage) {
					result.put("code", 0);
					result.put("msg", "文件的格式不正确");
					return result;
				}
			}
			result = UploadUtil.uplodeFile(file,fileName,TSHELVESPATH);
			if (!"1".equals(result.get("code").toString())) {
				return result;
			}
			tShelves.setContent(result.get("agtAttr").toString());
			tShelves.setSize(file.length());
		}
		tShelves.setIsOnLine(0);
		Sysopt user =(Sysopt)getSession().getAttribute("user");
		tShelves.setcUser(Long.toString(user.getSid()));
		tShelves.setcTime(new Date());
		int userRole =  (Integer) getSession().getAttribute("userRole");
		if (userRole == 1 || userRole == 2 || userRole == 21) {
			tShelves.setdType("1");
		}else if (userRole == 3 || userRole == 4) {
    		tShelves.setAgtCode(user.getAgtCode());
    		tShelves.setdType("2");
    	}else{
    		result.put("code", 0);
  	        result.put("msg", "权限不足，操作失败");
    	}
		long idNext  = dao.findSequence("seq_tshelves");
		tShelves.setSid(idNext);
		result =SyncTo(tShelves);
		if (!"1".equals(result.get("code").toString())) {
			log.error("错误信息："+(String)result.get("msg"));
   		 	throw new MdKnownRunTimeException((String)result.get("msg"));
		}
		tShelves = (TShelves) result.get("tShelves");
		add(tShelves);
		return result;
	}
	
	/**
	 * @Description: 同步开门惊喜资源到开放平台
	 * @param entity
	 * @return
	 */
	public Map<String, Object> SyncTo (TShelves tShelves){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String,String> map = new HashMap<String, String>();
			//平台使用
			if ("1".equals(tShelves.getdType())) {
				map.put("agt_num", Config.MD_OPEN_AGT_NUM);
				map.put("app_key", Config.MD_OPEN_APP_KEY);
			}else{
				map = tAgentService.getPlatAppKey(tShelves.getAgtCode());
			}
			MdOpenAddTShelvesJson json = MdOpenApi.addTShelves(tShelves,map.get("agt_num"),map.get("app_key"));
			if(json.isSuccess()){
				tShelves.setOpenSid(json.getData().getSid());
				result.put("tShelves", tShelves);
				result.put("code", 1);
      	        result.put("msg", "操作成功");
			}else{
				log.error("开门惊喜资源同步失败，json:"+json);
				result.put("code", 1);
      	        result.put("msg", "添加成功，开门惊喜资源同步失败:"+json.getMsg().toString().replaceAll("[^0-9\\u4e00-\\u9fa5]", ""));
			}
    	} catch (Exception e) {	
    		log.error("开门惊喜资源同步失败", e);
    		result.put("code", 0);
  	        result.put("msg", "开门惊喜资源同步失败");
    	}
		return result;
	}
	
	@Override
	public Map<String, String> getBySql(Long sid) {
		List<Map<String, String>> list= null;
		StringBuilder sql = new StringBuilder("select b.*,s.uname from tshelves b left join sysopt s on b.cuser=s.sid where b.sid=");
		sql.append(sid);
		list= dao.queryBySql(sql.toString());
		if (list.size()>0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	@LogAnnotation(operateDescribe="开门惊喜资源修改")  
	public Map<String, Object> updateMethod(TShelves tShelves, File file, String fileName) throws Exception {
		TShelves entry = get(tShelves.getSid());
		boolean ifUpload = false;
		if (file != null) {
			boolean isImage = ValidateUtil.isImage(file);
             if (!isImage) {
            	 result.put("code", 0);
            	 result.put("msg", "文件的格式不正确");
                 return result;
             }
			result = UploadUtil.uplodeFile(file,fileName,TSHELVESPATH);
			if (!"1".equals(result.get("code").toString())) {
				return result;
			}
			entry.setContent(result.get("agtAttr").toString());
			entry.setSize(file.length());
			ifUpload = true;
		}
		if (StringUtils.isNotBlank(tShelves.getName())) {
			entry.setName(tShelves.getName());
		}
		if (StringUtils.isNotBlank(tShelves.getcUrl())) {
			entry.setcUrl(tShelves.getcUrl());
		}
		entry.setExpectedIncome(tShelves.getExpectedIncome());
		entry.setAdDetails(tShelves.getAdDetails());
		entry.setSettlementMethod(tShelves.getSettlementMethod());
		if (!entry.getIfShare().equals(tShelves.getIfShare())) {
			if("0".equals(tShelves.getIfShare())){
				changeTStrategy(tShelves.getSid(),entry.getAgtCode());
			}
		}
		entry.setIfShare(tShelves.getIfShare());
		entry.setType(tShelves.getType());
		entry.setVisiAble(tShelves.getVisiAble());
		Sysopt user =(Sysopt)getSession().getAttribute("user");
		entry.setuUser(Long.toString(user.getSid()));
		entry.setuTime(new Date());
		result =SyncToEdit(entry,ifUpload);
		if (!"1".equals(result.get("code").toString())) {
   		 	throw new MdKnownRunTimeException((String)result.get("msg"));
		}
		update(entry);
		return result;
	}
	
	/**
	 * 资源不共享时剔除其他合作方社区
	 * @param shid
	 * @param agtCode
	 */
	private void changeTStrategy(Long shid, String agtCode) {
		TStrategy tStrategy = getLifeStrategy(shid);
		if (tStrategy == null || StringUtils.isBlank(tStrategy.getAgtCode())|| StringUtils.isBlank(tStrategy.getCommunityId())) {
			return;
		}
		if(tStrategy.getAgtCode().indexOf(","+agtCode+",")>-1){
			tStrategy.setAgtCode(","+agtCode+",");
		}else{
			tStrategy.setAgtCode("");
			tStrategy.setCommunityId("");
			updateLifeStrategy(tStrategy);
			return;
		}
		List<TCommunity> listComu = tCommunityService.listByAgtCodes(agtCode);
		String comuIds =  tStrategy.getCommunityId();
		StringBuffer comuids = new StringBuffer();
		for (TCommunity tCommunity : listComu) {
			String conuid = ","+tCommunity.getSid()+",";
			if (comuIds.indexOf(conuid)>-1) {
				comuids.append(tCommunity.getSid());
				comuids.append(",");
			}
		}
		if (comuids.length()==0) {
			tStrategy.setAgtCode("");
			tStrategy.setCommunityId("");
			updateLifeStrategy(tStrategy);
			return;
		}
		String cmu = comuids.toString();
		tStrategy.setCommunityId(","+cmu);
		updateLifeStrategy(tStrategy);
	}

	private void updateLifeStrategy(TStrategy tStrategy) {
		dao.update(tStrategy);
	}

	private TStrategy getLifeStrategy(Long shid) {
		StringBuffer sb = new StringBuffer("from TStrategy where shid=");
		sb.append(shid);
		return (TStrategy) dao.loadObject(sb.toString());
	}

	/**
	 * @param ifUpload 
	 * @Description: 同步开门惊喜资源到开放平台
	 * @param entity
	 * @return
	 */
	public Map<String, Object> SyncToEdit (TShelves tShelves, boolean ifUpload){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String,String> map = new HashMap<String, String>();
			//平台使用
			if ("1".equals(tShelves.getdType())) {
				map.put("agt_num", Config.MD_OPEN_AGT_NUM);
				map.put("app_key", Config.MD_OPEN_APP_KEY);
			}else{
				map = tAgentService.getPlatAppKey(tShelves.getAgtCode());
			}
			MdOpenBaseJson json = MdOpenApi.editTShelves(tShelves,map.get("agt_num"),map.get("app_key"),ifUpload);
			if(json.isSuccess()){
				result.put("code", 1);
      	        result.put("msg", "操作成功");
			}else{
				log.error("开门惊喜资源同步失败，json:"+json);
				result.put("code", 0);
      	        result.put("msg", "开门惊喜资源同步失败:"+json.getMsg().toString().replaceAll("[^0-9\\u4e00-\\u9fa5]", ""));
			}
    	} catch (Exception e) {	
    		log.error("开门惊喜资源同步失败", e);
    		result.put("code", 0);
  	        result.put("msg", "开门惊喜资源同步失败");
    	}
		return result;
	}
}
